package presentation.rest;

import com.sun.jersey.spi.resource.Singleton;
import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonGenerator;

import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.StreamingOutput;
import java.io.IOException;
import java.io.OutputStream;


@Singleton
@Path("hello")
public class HelloResource {

	private final static JsonFactory JSON_FACTORY = new JsonFactory();

	@GET
	@Produces(MediaType.APPLICATION_JSON)
	public Response hello(final @QueryParam("name") @DefaultValue("World") String name) {
		return Response.ok(new StreamingOutput() {
			@Override
			public void write(OutputStream output) throws IOException, WebApplicationException {
				JsonGenerator g = JSON_FACTORY.createJsonGenerator(output);
				g.writeStartObject();
				g.writeStringField("greeting", "Hello " + name + "!!!");
				g.writeEndObject();
				g.close();
			}
		}).build();
	}
}
